package com.jeespring.rocketmq.transaction;

import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.client.producer.*;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;

/**
 * @description SyncProducer
 * @author 张朝阳
 * @date 2021/1/10 15:30
 */
public class SyncProducer {
    public static void main(String[] args) throws Exception {
        TransactionMQProducer producer = new TransactionMQProducer("group1");

        producer.setNamesrvAddr("192.168.19.10:9876");
        producer.setTransactionListener(new TransactionListener() {
            
            /**
             * 执行本地事务
             */
            @Override
            public LocalTransactionState executeLocalTransaction(Message message, Object o) {
                if ("TAG-1".equals(message.getTags())){
                    return LocalTransactionState.COMMIT_MESSAGE;
                }
                if ("TAG-2".equals(message.getTags())){
                    return LocalTransactionState.ROLLBACK_MESSAGE;
                }
                if ("TAG-3".equals(message.getTags())){
                    return LocalTransactionState.UNKNOW;
                }
                return null;
            }

            /**
             * 事务消息状态回查
             */
            @Override
            public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
                System.out.println("回查的消息："+ messageExt.getTags());
                return LocalTransactionState.COMMIT_MESSAGE;
            }
        });

        producer.start();
        String[] tags = {"TAG-1","TAG-2","TAG-3"};
        for (int i = 0; i < 3; i++) {
            //public Message(String topic, String tags, byte[] body)
            String msg ="【" + tags[i] + "】事务消息" + i;
            Message message = new Message("order-topic",tags[i],msg.getBytes(RemotingHelper.DEFAULT_CHARSET));

            SendResult sendResult = producer.sendMessageInTransaction(message,null);

            System.out.println(JSON.toJSONString(sendResult));

        }
        //需要回查消息，不用立即shutdown
//        producer.shutdown();
    }
}
